//
//  HLMatchFateTipView.m
//  YueYue
//
//  Created by hulu001 on 2023/6/6.
//

#import "HLMatchFateTipView.h"
#import "HLMatchRequest.h"
#import "HLGCDTimerManager.h"
#import "HLCallTool.h"
#import <lottie_ios_Oc/LOTAnimationView.h>

@interface HLMatchFateTipView ()

@property (nonatomic, strong) QMUIButton *cancelButton;
@property (nonatomic, strong) UIImageView *leftAvatarView;
@property (nonatomic, strong) LOTAnimationView *animation;
@property (nonatomic, strong) LOTAnimationView *downAnimation;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UILabel *countDownLabel;
@property (nonatomic, strong) UIImageView *rightAvatarView;
@property (nonatomic, strong) UILabel *loadingLabel;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UIView *bottomView;
@end

@implementation HLMatchFateTipView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView
{
    self.backgroundColor = [UIColor qmui_colorWithHexString:@"#232A35"];
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 20;
    
    self.bottomView = [[UIView alloc] init];
    _bottomView.backgroundColor = [UIColor qmui_colorWithHexString:@"#232A35"];
    [self addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    
    self.cancelButton = [[QMUIButton alloc] init];
    [_cancelButton setTitle:@"取消匹配" forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColorWhite colorWithAlphaComponent:0.5] forState:UIControlStateNormal];
    [_cancelButton.titleLabel setFont:UIFontMake(13)];
    [self addSubview:_cancelButton];
    [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(16);
        make.right.mas_equalTo(-16);
    }];
    
    self.leftAvatarView = [[UIImageView alloc] initWithImage:UIImageMake(@"match_fate_avatar")];
    [self addSubview:_leftAvatarView];
    [_leftAvatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(40);
        make.right.equalTo(self.mas_centerX).offset(-28);
    }];
    
    self.animation = [[LOTAnimationView alloc] init];
    [_animation setAnimationNamed:@"matching"];
    _animation.frame = CGRectMake(0, 0, 30, 30);
    _animation.contentMode = UIViewContentModeScaleAspectFill;
    _animation.clipsToBounds = YES;
    _animation.userInteractionEnabled = NO;
    _animation.loopAnimation = YES;
    [self addSubview:_animation];
    [_animation mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_leftAvatarView);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(30);
    }];
    
    self.downAnimation = [[LOTAnimationView alloc] init];
    [_downAnimation setAnimationNamed:@"count_down"];
    _downAnimation.frame = CGRectMake(0, 0, 80, 80);
    _downAnimation.contentMode = UIViewContentModeScaleAspectFill;
    _downAnimation.clipsToBounds = YES;
    _downAnimation.userInteractionEnabled = NO;
    _downAnimation.loopAnimation = YES;
    _downAnimation.hidden = YES;
    [self addSubview:_downAnimation];
    [_downAnimation mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.size.mas_equalTo(80);
    }];
    
    self.timeLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(40) textColor:HLMainColor];
    _timeLabel.text = @"3";
    _timeLabel.hidden = YES;
    [self addSubview:_timeLabel];
    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_downAnimation);
    }];
    
    self.countDownLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(13) textColor:UIColorWhite];
    _countDownLabel.text = @"3 秒后将为您匹配";
    _countDownLabel.hidden = YES;
    [self addSubview:_countDownLabel];
    [_countDownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(_downAnimation.mas_bottom).offset(22);
    }];
    
    
    self.rightAvatarView = [[UIImageView alloc] init];
    _rightAvatarView.contentMode = UIViewContentModeScaleAspectFit;
    _rightAvatarView.layer.masksToBounds = YES;
    _rightAvatarView.layer.cornerRadius = 30;
    _rightAvatarView.layer.borderWidth = 2;
    _rightAvatarView.layer.borderColor = [UIColor qmui_colorWithHexString:@"#F48B01"].CGColor;
    [self addSubview:_rightAvatarView];
    [_rightAvatarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(60);
        make.centerY.equalTo(_leftAvatarView);
        make.left.equalTo(self.mas_centerX).offset(28);
    }];
    
    [_rightAvatarView sd_setImageWithURL:[NSURL URLWithString:HLRunTime.shareInstance.mine.avatar] placeholderImage:[HLUIHelper avatarPlaceholder]];
    
    self.loadingLabel = [[UILabel alloc] qmui_initWithFont:UIFontMediumMake(16) textColor:UIColorWhite];
    _loadingLabel.text = @"正在连接中···";
    [self addSubview:_loadingLabel];
    [_loadingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(_leftAvatarView.mas_bottom).offset(16);
    }];
    
    self.tipLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(13) textColor:[UIColorWhite colorWithAlphaComponent:0.5]];
    _tipLabel.text = @"此时此刻，TA也在等待和你相遇～";
    [self addSubview:_tipLabel];
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(_loadingLabel.mas_bottom).offset(8);
    }];
}

- (void)countDown
{
    self.leftAvatarView.hidden = YES;
    self.animation.hidden = YES;
    self.rightAvatarView.hidden = YES;
    self.loadingLabel.hidden = YES;
    self.tipLabel.hidden = YES;
    
    
    self.downAnimation.hidden = NO;
    self.countDownLabel.hidden = NO;
    self.timeLabel.hidden = NO;
}

- (void)countUp
{
    self.downAnimation.hidden = YES;
    self.countDownLabel.hidden = YES;
    self.timeLabel.hidden = YES;
    
    self.leftAvatarView.hidden = NO;
    self.animation.hidden = NO;
    self.rightAvatarView.hidden = NO;
    self.loadingLabel.hidden = NO;
    self.tipLabel.hidden = NO;
}

-(void)updateTime:(NSInteger)time
{
    _timeLabel.text = [NSString stringWithFormat:@"%ld", time];
    _countDownLabel.text = [NSString stringWithFormat:@"%ld 秒后将为您匹配", time];
}

+ (void)showWithLabel:(nullable NSString *)label callback:(HLCommonCallbackBoolBlock)callback;
{
    CGFloat height = 238 + SafeAreaInsetsConstantForDeviceWithNotch.bottom;
    HLMatchFateTipView *containerView = [[HLMatchFateTipView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
    [containerView countDown];
    QMUIModalPresentationViewController *modalViewController = [[QMUIModalPresentationViewController alloc] init];
    modalViewController.contentViewMargins = UIEdgeInsetsMake(SCREEN_HEIGHT-height, 0, 0, 0);
    modalViewController.contentView = containerView;
    [modalViewController showWithAnimated:YES completion:^(BOOL finished) {
        
        [containerView.downAnimation play];
        
        __block NSInteger countDown = 4;
        NSString *timerName = @"countDown";
        __block NSInteger countUp = 2;
        NSString *timerNameUp = @"countUp";
        
        containerView.cancelButton.qmui_tapBlock = ^(__kindof UIControl *sender) {
            [modalViewController hideWithAnimated:NO completion:nil];
            [HLGCDTimerManager cancel:timerName];
            [HLGCDTimerManager cancel:timerNameUp];
        };
        [HLGCDTimerManager scheduledTimerWithName:timerName interval:1 delaySecs:0 queue:dispatch_get_main_queue() repeats:YES action:^(NSInteger actionTimes) {
            countDown -= 1;
            [containerView updateTime:countDown];
            if (countDown == 0){
                [HLGCDTimerManager cancel:timerName];
                [containerView countUp];
                [containerView.animation play];
                
                [HLGCDTimerManager scheduledTimerWithName:timerNameUp interval:1 delaySecs:0 queue:dispatch_get_main_queue() repeats:YES action:^(NSInteger actionTimes) {
                    countUp -= 1;
                    if (countUp == 0){
                        [HLGCDTimerManager cancel:timerNameUp];
                        if (label.length > 0){
                            [self randomUserWithController:modalViewController label:label callback:callback];
                        } else {
                            [self randomUserWithController:modalViewController callback:callback];
                        }
                    }
                }];
                [HLGCDTimerManager start:timerNameUp];
            }
        }];
        [HLGCDTimerManager start:timerName];

    }];
    
    [containerView.cancelButton setQmui_tapBlock:^(__kindof UIControl *sender) {
        [modalViewController hideWithAnimated:YES completion:nil];
    }];
}


+ (void)randomUserWithController:(QMUIModalPresentationViewController *)controller callback:(HLCommonCallbackBoolBlock)callback
{
    HLMatchRequest *matchRequest = [[HLMatchRequest alloc] initWithType:HLMatchTypeFate params:@{}];
    [matchRequest startWithCompletionBlockWithSuccess:^(__kindof HLMatchRequest * _Nonnull request) {
        if (request.isSuccess){
            [self hidAnimateWithUser:[request fateUser] controller:controller callback:callback];
        } else {
            [controller hideWithAnimated:NO completion:nil];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [controller hideWithAnimated:NO completion:nil];
    }];
}


+ (void)randomUserWithController:(QMUIModalPresentationViewController *)controller
                           label:(NSString *)label
                        callback:(HLCommonCallbackBoolBlock)callback
{
    HLMatchRequest *matchRequest = [[HLMatchRequest alloc] initWithType:HLMatchTypeLabel params:@{@"labelCodes":label}];
    [matchRequest startWithCompletionBlockWithSuccess:^(__kindof HLMatchRequest * _Nonnull request) {
        if (request.isSuccess){
            HLHomeListModel *user = [request fateUser];
            if (user != nil){
                [self hidAnimateWithUser:user controller:controller callback:callback];
            } else {
                [QMUITips showWithText:@"当前人数不足"];
                [controller hideWithAnimated:NO completion:nil];
            }
        }
    } failure:nil];
}

+ (void)hidAnimateWithUser:(HLHomeListModel *)randomUser controller:(QMUIModalPresentationViewController *)controller
                  callback:(HLCommonCallbackBoolBlock)callback
{
    [controller hideWithAnimated:NO completion:^(BOOL finished) {
        HLUserInfoModel *user = [[HLUserInfoModel alloc] init];
        user.userId = randomUser.uid;
        user.avatar = randomUser.avatar;
        user.nickName = randomUser.nickName;
        user.videoType = [randomUser videoType];
        [[HLCallTool shareInstance] matchUser:user OnVC:[QMUIHelper visibleViewController] callback:callback];
    }];
    
}


@end
